import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx'
import { Browser, BrowserHrm, Upload } from 'weaver-mobile-page'
import { withRouter } from 'react-router-dom';
import { Tools, TextareaItem, Icon, Select, List, DatePicker, Modal, Toast, Button, Switch, Tag } from 'weaver-mobile';
import * as TaskMainApis from '../../../../api/task/taskMain'
import * as Util from '../../../../util'

// const prompt = Modal.prompt
const FormItem = List.FormItem
const { DatePickerInput } = DatePicker
const getLabel = Tools.getLabel

@inject("taskDetailBaseinfoStore", "taskDetailStore", "taskCommonStore")
@withRouter
@observer
class Baseinfo extends React.Component {

    constructor(props) {
        super(props)
        this.state = { ...props }
    }

    componentWillMount() {
        const { detail } = this.state
        const { initValues } = this.props.taskDetailBaseinfoStore
        if (detail) {
            initValues(detail)
        }
    }

    componentWillReceiveProps(newProps) {
        const { initValues } = this.props.taskDetailBaseinfoStore

        if (newProps.detail != this.state.detail) {
            this.setState({
                detail: newProps.detail
            })
            if (newProps.detail) {
                initValues(newProps.detail)
            }
        }
    }

    componentWillUnmount() {
        // const { clearValues } = this.props.taskDetailBaseinfoStore
        // clearValues()
    }

    onSaveBtnClick = () => {
        if (this.checkedPass()) {
            this.doSave()
        }
    }

    checkedPass = () => {
        const { taskCommonStore } = this.props
        const { name, principalArray, begindate, enddate } = this.props.taskDetailBaseinfoStore.editParams
        if (!name) {
            taskCommonStore.warn(getLabel(504646, '任务名称不能为空'))
            return false
        }

        if (principalArray.length == 0) {
            taskCommonStore.warn(getLabel('508801', '责任人不能为空'))
            return false
        }

        if (begindate && enddate && begindate > enddate) {
            taskCommonStore.warn(getLabel(16721, '开始日期不能大于结束日期'))
            return false
        }

        return true
    }

    doSave = () => {
        const { detail } = this.state
        const { taskCommonStore } = this.props
        const { changeTaskDetail,changeTaskDetailField } = this.props.taskDetailStore
        const { taskid } = this.props.taskDetailBaseinfoStore
        const { name, todotype, parentArray, level, principalArray, partnerArray, sharerArray,
            begindate, enddate, tagArray, remark, risk, difficulty, assist, showallsub } = this.props.taskDetailBaseinfoStore.editParams

        let requestParamArr = []
        if (detail.name != name) {
            requestParamArr.push({
                fieldname: "name",
                fieldvalue: name,
                fieldtype: "str"
            })
        }

        if (detail.todotype != todotype) {
            requestParamArr.push({
                fieldname: "todotype",
                fieldvalue: todotype,
                fieldtype: "str"
            })
        }

        let newIdsStr = parentArray.map((d, i) => { return d.id }).join(",")
        let oldIdsStr = detail.parentid || ""
        let delValue
        let addValue
        if (newIdsStr != oldIdsStr) {
            requestParamArr.push({
                fieldname: "parentid",
                fieldvalue: newIdsStr,
                fieldtype: "str"
            })
        }

        if (detail.lev != level) {
            requestParamArr.push({
                fieldname: "level",
                fieldvalue: level,
                fieldtype: "str"
            })
        }

        newIdsStr = principalArray.map((d, i) => { return d.id }).join(",")
        oldIdsStr = detail.principalid || ""
        let isprincipalid = false;
        if (newIdsStr != oldIdsStr) {
            requestParamArr.push({
                fieldname: "principalid",
                fieldvalue: newIdsStr,
                fieldtype: "str"
            })
            isprincipalid = true;
        }

        newIdsStr = "," + partnerArray.map((d, i) => { return d.id }).join(",") + ","
        oldIdsStr = "," + (detail.partnerarry || []).map((d, i) => { return d.id }).join(",") + ","
        delValue = Util.ArrayDiffer(oldIdsStr, newIdsStr, 1)
        addValue = Util.ArrayDiffer(oldIdsStr, newIdsStr.split(","), 2)
        if (newIdsStr != oldIdsStr) {
            requestParamArr.push({
                fieldname: "partnerid",
                fieldvalue: newIdsStr,
                fieldtype: "str",
                addvalue: addValue,
                delvalue: delValue
            })
        }

        newIdsStr = "," + sharerArray.map((d, i) => { return d.id }).join(",") + ","
        oldIdsStr = "," + (detail.sharerarry || []).map((d, i) => { return d.id }).join(",") + ","
        delValue = Util.ArrayDiffer(oldIdsStr, newIdsStr, 1)
        addValue = Util.ArrayDiffer(oldIdsStr, newIdsStr.split(","), 2)
        if (newIdsStr != oldIdsStr) {
            requestParamArr.push({
                fieldname: "sharerid",
                fieldvalue: newIdsStr,
                fieldtype: "str",
                addvalue: addValue,
                delvalue: delValue
            })
        }

        if (detail.begindate != begindate) {
            requestParamArr.push({
                fieldname: "begindate",
                fieldvalue: begindate,
                fieldtype: "str"
            })
        }

        if (detail.enddate != enddate) {
            requestParamArr.push({
                fieldname: "enddate",
                fieldvalue: enddate,
                fieldtype: "str"
            })
        }

        newIdsStr = "," + tagArray.map((d, i) => { return d.id }).join(",") + ","
        oldIdsStr = "," + (detail.tagarry || []).map((d, i) => { return d.id }).join(",") + ","
        delValue = Util.ArrayDiffer(oldIdsStr, newIdsStr, 1)
        addValue = Util.ArrayDiffer(oldIdsStr, newIdsStr.split(","), 2)
        if (newIdsStr != oldIdsStr) {
            requestParamArr.push({
                fieldname: "tag",
                fieldvalue: newIdsStr,
                fieldtype: "str",
                addvalue: addValue,
                delvalue: delValue
            })
        }

        if (detail.remark != remark) {
            requestParamArr.push({
                fieldname: "remark",
                fieldvalue: remark,
                fieldtype: "str"
            })
        }

        if (detail.risk != risk) {
            requestParamArr.push({
                fieldname: "risk",
                fieldvalue: risk,
                fieldtype: "str"
            })
        }

        if (detail.difficulty != difficulty) {
            requestParamArr.push({
                fieldname: "difficulty",
                fieldvalue: difficulty,
                fieldtype: "str"
            })
        }

        if (detail.assist != assist) {
            requestParamArr.push({
                fieldname: "assist",
                fieldvalue: assist,
                fieldtype: "str"
            })
        }

        if (detail.showallsub != showallsub) {
            requestParamArr.push({
                fieldname: "showallsub",
                fieldvalue: showallsub,
                fieldtype: "str"
            })
        }

        if (requestParamArr.length > 0) {
            taskCommonStore.showLoading()
            TaskMainApis.taskUpdateInfo({
                taskId: taskid,
                datas: JSON.stringify(requestParamArr)
            }).then(res => {
                taskCommonStore.closeLoading()
                if (res.status == "1") {
                    taskCommonStore.saveSuccess()
                    changeTaskDetail(Object.assign({}, detail, {
                        name,
                        todotype,
                        parentid: parentArray.map((d, i) => { return d.id }).join(","),
                        parentname: parentArray.map((d, i) => { return d.name }).join(","),
                        lev: level,
                        principalid: principalArray.map((d, i) => { return d.id }).join(","),
                        principalname: principalArray.map((d, i) => { return d.name }).join(","),
                        partnerarry: [...partnerArray],
                        sharerarry: [...sharerArray],
                        tagarry: res.tagList || [...tagArray],
                        begindate,
                        enddate,
                        remark,
                        risk,
                        difficulty,
                        assist,
                        showallsub
                    }))
                    if(isprincipalid){
                        changeTaskDetailField("taskstatus", "4")
                    }
                }
            })
        } else {
            taskCommonStore.remind(getLabel(513866, '暂无修改！'))
        }
    }

    // delTag = (tagid, columnarray) => {
    //     const { taskCommonStore } = this.props
    //     const { taskid, editParams, changeEditparamsField } = this.props.taskDetailBaseinfoStore
    //     TaskMainApis.editTaskInfo({
    //         taskId: taskid,
    //         fieldname: "tag",
    //         fieldtype: "str",
    //         fieldvalue: "," + editParams[columnarray].filter((d, i) => { return d.id != tagid }).map((d, i) => { return d.id }).join(",") + ",",
    //         delvalue: tagid
    //     }).then(res => {
    //         if (res.status == "1") {
    //             changeEditparamsField(columnarray, editParams[columnarray].filter((d, i) => { return d.id != tagid }))
    //             taskCommonStore.updateSuccess()
    //         }
    //     })
    // }

    resetAmListCss = (ref) => {
        ref.classList.add("workrelate-mobile-am-list-no-extra")
        ref.classList.add("workrelate-mobile-am-picker-no-padding")
        ref.classList.add("workrelate-condition-right")
    }
    onConfirmBtnClick(type,_v){
        const {taskDetailStore,taskCommonStore} = this.props;
        if(type==5){
            let _this = this;
            Modal.prompt(getLabel(516927, '请填写拒绝理由'), _v, [
                {text: getLabel(201, '取消'),style: 'default'},
                {text: getLabel('826', '确定'),
                  onPress: (value) => {
                    if(value==''){
                        taskCommonStore.remind(getLabel(516927,'请填写拒绝理由'));
                        return;
                    }
                    taskDetailStore.taskChangeStatus({status:type,infos:getLabel(515084,'确认要拒绝此任务吗？'),refuseval:value,
                                        doback:function(){
                                            _this.props.history.push("/taskHome");
                                        }});
                  }
                }
            ],'text-required')
        }else{
            taskDetailStore.taskChangeStatus({status:type,infos:_v});
        }
    }
    render() {
        const { taskid } = this.props.taskDetailBaseinfoStore
        let { columnList, canedit,isconfirm, editParams, changeEditparamsField, getOptions,
            taskDetailSupTaskBrowserStore, taskDetailHrmPrincipalBrowserStore, taskDetailTagBrowserStore,
            taskDetailHrmPartnerBrowserStore, taskDetailHrmSharerBrowserStore } = this.props.taskDetailBaseinfoStore
        // canedit = false
        if (columnList && columnList.map((d, i) => d.columninfo).indexOf("tag") === -1) {
            columnList.push({
                type: "2",
                columninfo: "tag",
                columnarray: "tagArray",
                languageid: "30878",
                name: "标签",
                browssingle: false,
                browstype: "wrltag"
            })
        }

        return (
            <div key={"baseinfo" + canedit ? "1" : "0"} className="workrelate-mobile-task-baseinfo-wrapper" ref={ref => { ref && taskid && !canedit && this.resetAmListCss(ref) }}>
                <div className="content-wrapper">
                    {
                        columnList && columnList.length > 0 && columnList.map((element, idx) => {
                            let _canedit = canedit
                            let isShow = element.fieldright != "0"
                            let fieldright = element.fieldright || ""
                            if (!_canedit && fieldright && parseInt(fieldright) > 1) {
                                fieldright = "1"
                            }
                            if (_canedit && fieldright) {
                                _canedit = parseInt(fieldright) > 1
                            }

                            if (element.type === "1" || element.type === "5") {
                                return ( isShow &&
                                    <List>
                                        <FormItem
                                            required={element.columninfo == "name" && !editParams[element.columninfo]}
                                            extra={_canedit && <Icon type="editor" size="xxs" />}
                                            label={getLabel(element.languageid, element.name)}
                                            line
                                            noBorder
                                            content={
                                                <TextareaItem
                                                    placeholder={_canedit ? getLabel('383036', '请输入内容') : ""}
                                                    editable={_canedit}
                                                    autoHeight
                                                    value={editParams[element.columninfo]}
                                                    onChange={val => { changeEditparamsField(element.columninfo, val) }}
                                                />
                                            }
                                        />
                                    </List>
                                )
                            } else if (element.type === "2") {
                                if (["principalid", "partnerid", "sharerid"].indexOf(element.columninfo) > -1) {
                                    let store
                                    if (element.columninfo === "principalid") {
                                        store = taskDetailHrmPrincipalBrowserStore
                                    } else if (element.columninfo === "partnerid") {
                                        store = taskDetailHrmPartnerBrowserStore
                                    } else {
                                        store = taskDetailHrmSharerBrowserStore
                                    }
                                    return ( isShow &&
                                        <List className={_canedit ? "" : "workrelate-am-list-no-arrow"}>
                                            <BrowserHrm
                                                store={store}
                                                placeholder={_canedit ? "" : <span>&nbsp;</span>}
                                                label={getLabel(element.languageid, element.name)}
                                                isSingle={element.browssingle}
                                                hasAdvanceSerach
                                                type={element.browstype}
                                                onChange={(...arg) => {
                                                    changeEditparamsField(element.columnarray, arg[2])
                                                }}
                                                valueArray={editParams[element.columnarray]}
                                                viewAttr={fieldright ? parseInt(fieldright) : (_canedit ? (element.columninfo === "principalid" ? 3 : 2) : 1)}
                                            />
                                        </List>
                                    )
                                } else {
                                    let store
                                    if (element.columninfo === "parentid") {
                                        store = taskDetailSupTaskBrowserStore
                                        return ( isShow && 
                                            <List className={_canedit ? "" : "workrelate-am-list-no-arrow"}>
                                                <Browser
                                                    store={store}
                                                    placeholder={_canedit ? "" : <span>&nbsp;</span>}
                                                    dataURL={element.browscompurl ? element.browscompurl : "/api/public/browser/data/"}
                                                    // conditionURL="/api/workrelate/task/getTaskTabInfo/"
                                                    label={getLabel(element.languageid, element.name)}
                                                    isSingle={element.browssingle}
                                                    type={element.browscompurl ? "" : element.browstype}
                                                    dataParams={{ parentid: taskid }}
                                                    // linkUrl="/spa/workrelate/static/index.html?#/main/workrelate/task/taskDetail?id="
                                                    onChange={(...arg) => {
                                                        changeEditparamsField(element.columnarray, arg[2])
                                                    }}
                                                    valueArray={editParams[element.columnarray]}
                                                    viewAttr={fieldright ? parseInt(fieldright) : (_canedit ? 2 : 1)}
                                                />
                                            </List>
                                        )
                                    } else if (element.columninfo === "tag") {
                                        store = taskDetailTagBrowserStore
                                        return ( isShow &&
                                            <div>
                                                <List className="workrelate-am-list-arrow-center workrelate-am-list-has-extra" key={new Date().getTime() + "tag"}>
                                                    <FormItem
                                                        extra={
                                                            <div onClick={() => {
                                                                this.props.history.push(store.path)
                                                            }}>
                                                                <Icon type="right" />
                                                            </div>
                                                        }
                                                        label={getLabel(element.languageid, element.name)}
                                                        line
                                                        noBorder
                                                        content={
                                                            <div
                                                                className="tag-content-wrapper"
                                                                onClick={() => {
                                                                    this.props.history.push(store.path)
                                                                }}
                                                                ref={ref => {
                                                                    if (ref) {
                                                                        ref.parentNode.style.height = ref.clientHeight + "px"
                                                                    }
                                                                }}
                                                            >
                                                                {
                                                                    editParams[element.columnarray].map((d, i) => {
                                                                        return (
                                                                            <div
                                                                                className="content-wrapper"
                                                                            >
                                                                                <div className="text" style={{ background: d.color || "green" }}>
                                                                                    {d.name}
                                                                                </div>
                                                                            </div>
                                                                        )
                                                                    })
                                                                }
                                                                {
                                                                    editParams[element.columnarray].length === 0 &&
                                                                    <div className="tag-placeholder-wrapper">
                                                                        {"请输入"}
                                                                    </div>
                                                                }
                                                            </div>
                                                        }
                                                    />
                                                </List>
                                                <div style={{ display: "none" }}>
                                                    <Browser
                                                        store={store}
                                                        placeholder={_canedit ? "" : <span>&nbsp;</span>}
                                                        dataURL={element.browscompurl ? element.browscompurl : "/api/public/browser/data/"}
                                                        label={getLabel(element.languageid, element.name)}
                                                        isSingle={element.browssingle}
                                                        type={"wrltag"}
                                                        onChange={(...arg) => {
                                                            changeEditparamsField(element.columnarray, arg[2].sort((a, b) => parseInt(a.id) - parseInt(b.id)))
                                                            if (!canedit) {
                                                                this.doSave()
                                                            }
                                                        }}
                                                        valueArray={editParams[element.columnarray]}
                                                        // viewAttr={canedit ? 2 : 1}
                                                        viewAttr={2}
                                                        dataParams={{ selectedIds: editParams[element.columnarray].map(d => d.id).join(",") }}
                                                    />
                                                </div>
                                            </div>
                                        )
                                    }
                                }
                            } else if (element.type === "3") {
                                return ( isShow && 
                                    <List>
                                        <FormItem
                                            line
                                            noBorder
                                            content={
                                                <Select
                                                    label={getLabel(element.languageid, element.name)}
                                                    value={editParams[element.columninfo]}
                                                    options={getOptions(element.columnarray)}
                                                    onChange={val => changeEditparamsField(element.columninfo, val)}
                                                    viewAttr={ fieldright ? parseInt(fieldright) : (_canedit ? 2 : 1)}
                                                />
                                            }
                                        />
                                    </List>
                                )
                            } else if (element.type === "4") {
                                return ( isShow &&
                                    <List>
                                        <FormItem
                                            label={getLabel(element.languageid, element.name)}
                                            noBorder
                                            line
                                            content={
                                                <DatePickerInput
                                                    placeholder={_canedit ? getLabel(83869, '请输入') : <span>&nbsp;</span>}
                                                    mode={"date"}
                                                    value={editParams[element.columninfo]}
                                                    onChange={(val) => changeEditparamsField(element.columninfo, val)}
                                                    disabled={!_canedit}
                                                />
                                            }
                                        />
                                    </List>
                                )
                            } else if (element.type === "7") {
                                return ( isShow &&
                                    <List className="switch-list">
                                        <FormItem
                                            label={getLabel(element.languageid, element.name)}
                                            noBorder
                                            line
                                            content={
                                                <Switch
                                                    checked={editParams.showallsub == 0 ? false : true}
                                                    onClick={val => changeEditparamsField(element.columninfo, val ? "1" : "0")}
                                                    disabled={!_canedit}
                                                />
                                            }
                                        />
                                    </List>
                                )
                            }
                        })
                    }
                </div>
                {
                    canedit && editParams.status!=5 &&
                    <div className="save-btn-wrapper" onClick={this.onSaveBtnClick}>
                        <Button type="primary">{getLabel(86, '保存')}</Button>
                    </div>
                }
                {
                    canedit && editParams.status==5 &&
                    <div>
                    <div className="confirm-btn-wrapper" onClick={()=>this.onConfirmBtnClick(102,getLabel(515097,'确认要重新向责任人发送此任务吗？'))}>
                        <Button type="ghost">{getLabel(514155,'重发')}</Button>
                    </div>
                    <div className="confirm-btn-wrapper" onClick={this.onSaveBtnClick}>
                        <Button type="primary">{getLabel(86, '保存')}</Button>
                    </div></div>
                }
                {
                    isconfirm && <div>
                    <div className="confirm-btn-wrapper" onClick={()=>this.onConfirmBtnClick(100,getLabel(515080,'确认要接收此任务吗？'))}>
                        <Button type="primary">{getLabel(18526,'接收')}</Button>
                    </div>
                    <div className="confirm-btn-wrapper" onClick={()=>this.onConfirmBtnClick(5)}>
                        <Button type="ghost">{getLabel(25659,'拒绝')}</Button>
                    </div>
                    </div>
                }
            </div>
        )
    }
}

export default Baseinfo
